<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Categories extends AdminBase {
	public function __construct()
    {
        parent::__construct();
    }

	public function index()
	{
        $this->db->order_by('order','DESC');
        $menu = $this->db->get('category')->result_array();
		$this->admin_view('categories','分类管理',array('categories'=>$menu));
	}

	public function add()
	{
		$post = $this->input->post();
		$result = $this->db->insert('category', array('name'=>$post['name'],'parent_id'=>$post['pId']));
		return $this->db->insert_id();
	}

	public function delete(){
		$id = $this->input->post('id');
		$ids = self::getChildIds($id);
		foreach($ids as $item){
			$this->db->delete('category',array('id'=>$item['id']));
		}
		$this->db->delete('category',array('id'=>$id));
	}


	private function getChildIds($pid){
		$child = $this->db->select('id')->get_where('category',array('parent_id'=>$pid))->result_array();
		foreach($child as $item){
			$child = array_merge($child,self::getChildIds($item['id']));
		}
		return $child;
	}

}
